package com.syp.hehe.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

public final class PicDiskAdapterUtil {
	
	public static byte[] read(String path) {
		byte[] bytes = null;
		ByteArrayOutputStream baos = null;		
		BufferedInputStream bis = null;		
		try {
			baos = new ByteArrayOutputStream();
			bis = new BufferedInputStream(new FileInputStream(path));
			int size = 0;
			byte[] buff = new byte[8 * 1024];
			while ((size = bis.read(buff)) != -1) {
				baos.write(buff, 0, size);
			}
			bytes = baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bytes;
	}

	public static void write(MultipartFile file, String path) {
		BufferedOutputStream bos = null;
		try {
			int sepindex = path.lastIndexOf("/");
			String dir = path.substring(0, sepindex);
			String pic = path.substring(sepindex + 1);
			File fdir = new File(dir);
			if (!fdir.exists()) {
				fdir.mkdir();
			}
			File fpic = new File(dir, pic);
			bos = new BufferedOutputStream(new FileOutputStream(fpic));

			InputStream is = file.getInputStream();
			int size = 0;
			byte[] buff = new byte[8 * 1024];
			while ((size = is.read(buff)) != -1) {
				bos.write(buff, 0, size);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bos != null) {
					bos.flush();
					bos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
